package com.heima.home.service.impl;

import com.heima.home.exception.CustomException;
import com.heima.home.mapper.FavoritesMapper;
import com.heima.home.mapper.PropertyMapper;
import com.heima.home.entity.Favorites;
import com.heima.home.entity.Properties;
import com.heima.home.service.FavoritesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class FavoritesServiceImpl implements FavoritesService {
    @Autowired
    private FavoritesMapper favoritesMapper;
    
    @Autowired
    private PropertyMapper propertyMapper;
    @Override
    public List<Favorites> findAll(Integer currentUserId) {
        return favoritesMapper.findAll(currentUserId);
    }

    @Override
    public int cancelFavorites(Integer propertyId, Integer userId) {
        return favoritesMapper.cancelFavorites(propertyId,userId);
    }

    @Override
    public int addFavorites(Favorites favorites) {
        // 验证房源ID是否存在
        if (favorites.getPropertyId() == null) {
            throw new CustomException("房源ID不能为空");
        }
        
        Properties property = propertyMapper.selectById(favorites.getPropertyId().longValue());
        if (property == null) {
            throw new CustomException("房源不存在，无法添加收藏");
        }
        
        // 设置创建时间
        if (favorites.getCreatedAt() == null) {
            favorites.setCreatedAt(new Date());
        }
        
        return favoritesMapper.addFavorites(favorites);
    }
}
